import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [

    {
        path: '/login',
        name: 'login',
        component: () => import('../views/Login.vue')
    },
    // {
    //     path: '/register',
    //     name: 'Register',
    //     component: () => import('../views/Register.vue')
    // },
    {
        path: '/frontLogin',
        name: 'FrontLogin',
        component: () => import('../views/front/Login.vue')
    },
    {
        path: '/frontRegister',
        name: 'FrontRegister',
        component: () => import('../views/front/Register.vue')
    },
    {
        path: '/404',
        name: '404',
        component: () => import('../views/404.vue'),
    },
    {
        path: '/front',
        name: 'front',
        component: () => import('../views/front/FrontManage.vue'),
        children:[
            {
                path: 'home',
                name: 'FrontHome',
                component: () => import('../views/front/Home.vue')
            },
            {
                path: 'item1',
                name: 'Item1',
                component: () => import('../views/front/Item1.vue')
            },
            {
                path: 'FrontPerson',
                name: 'FrontPerson',
                component: () => import('../views/front/Person.vue')
            },
            {
                path: 'password',
                name: 'FrontPassword',
                component: () => import('../views/front/Password')
            },
            {
                path: 'video',
                name: 'Video',
                component: () => import('../views/front/Video.vue')
            },
            {
                path: 'VideoDetail',
                name: 'VideoDetail',
                component: () => import('../views/front/VideoDetail.vue')
            },
            {
                path: 'article',
                name: 'FrontArticle',
                component: () => import('../views/front/Article.vue')
            },
            {
                path: 'articleDetail',
                name: 'ArticleDetail',
                component: () => import('../views/front/ArticleDetail.vue')
            },
            {
                path: 'goodsPlusDetail',
                name: 'GoodsPlusDetail',
                component: () => import('../views/front/GoodsPlusDetail.vue')
            },
            {
                path: 'cart',
                name: 'Cart',
                component: () => import('../views/front/Cart.vue')
            },
            {
                path: 'ordersPlus',
                name: 'OrdersPlus',
                component: () => import('../views/front/OrdersPlus.vue')
            },
            {
                path: 'im',
                name: 'Im',
                component: () => import('../views/front/Im.vue')
            },
            {
                path: 'exam',
                name: 'Exam',
                component: () => import('../views/front/Exam.vue')
            },
            {
                path: 'paper',
                name: 'Paper',
                component: () => import('../views/front/Paper.vue')
            },
        ]
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
// router.match 是指用于在路由系统中匹配 URL 路径的方法。不同的框架或库具有不同的实现方式。
// 一般来说，当你的应用程序接收到一个 URL 请求时，路由器（router）会使用 router.match 方法来找到与该 URL 匹配的处理函数或组件。

// 提供一重置路由的方法
export const resetRouter = () => {
    router.match = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    })
}

// 注意刷新页面会导致路由重置
//设置动态路由
export const setRoutes = () => {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {

        // 获取当前的路由对象名称数组  把name映射成一个数组
        const currentRoutes = router.getRoutes().map(v => v.name)
        // 当不包含Manage
        if (!currentRoutes.includes('Manage')) {
            // 拼装动态路由
            const manageRoute = {
                path: '/', name: 'Manage', component: () => import('../views/Manage.vue'),
                redirect: "/home", children: [
                    {path: 'person', name: '个人信息', component: () => import('../views/Person.vue')},
                    {path: 'password', name: '修改密码', component: () => import('../views/Password.vue')},
                    {path: 'handlePaper', name: '阅卷', component: () => import('../views/HandlePaper.vue')}
                ]
            }
            const menus = JSON.parse(storeMenus)
            menus.forEach(item => {

                // 仅当path不为空的时候才去设置路由
                if (item.path) {
                    // replace("/","") 把/替换为 "" 空
                    let itemMenu = {
                        path: item.path.replace("/", ""),
                        name: item.name,
                        component: () => import('../views/' + item.pagePath + '.vue')
                    }
                    manageRoute.children.push(itemMenu)

                    //数组的长度大于零（即存在子元素）
                } else if (item.children.length) {
                    item.children.forEach(item => {
                        if (item.path) {

                            let itemMenu = {
                                path: item.path.replace("/", ""),
                                name: item.name,
                                component: () => import('../views/' + item.pagePath + '.vue')
                            }
                            manageRoute.children.push(itemMenu)
                        }
                    })
                }
            })
            // 动态添加到现在的路由对象中去
            router.addRoute(manageRoute)
        }
    }
}

// 重置我就再次set一次路由
setRoutes()

//路由守卫
//它将在每次导航之前（即路由发生变化之前）被调用。
router.beforeEach((to, from, next) => {
    localStorage.setItem("currentPathName", to.name) //设置当前路由名称，为了在Header组件中去使用 to.name是路由的name
    store.commit("setPath")  //触发store的数据更新

    // 未找到路由的情况
    // 因此，if (!to.matched.length) 的意思是如果当前路由的匹配长度为0，即没有匹配任何路由规则的情况下，执行相应的操作。
    if (!to.matched.length) {
        const storeMenus = localStorage.getItem("menus")
        // 如果menus不在
        if (storeMenus) {
            // next("/404")
            next("front/home")
        } else {
            // 跳回登录页面
            next("/login")
        }
    }
    //其他的情况就放行路由
    next()
})

export default router
